package ee.ttu.rakarh.commands;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ee.ttu.rakarh.model.data.dao.UserAuthDAO;
import ee.ttu.rakarh.model.data.dao.UserAuthDAOImpl;
import ee.ttu.rakarh.model.data.entities.User;
import ee.ttu.rakarh.other.AeSimpleMD5;

public class Login implements Command {
	private static final Logger LOG = Logger.getLogger(Login.class);

	@Override
	public Boolean execute(HttpServletRequest request,
			HttpServletResponse response) {
		Boolean result = false;
		
		UserAuthDAO userImpl = new UserAuthDAOImpl();
		User user = null;
		
		LOG.info(request.getParameter("username"));
		LOG.info(request.getParameter("password"));
		LOG.info(request.getSession().getAttribute("username"));
		LOG.info(request.getSession().getAttribute("password"));
		
		String username = (String) (request.getParameter("username") == null ? request.getSession().getAttribute("username") : request.getParameter("username"));
		String password = null;
		try {
			password = (String) (request.getParameter("password") == null ? request.getSession().getAttribute("password") : AeSimpleMD5.MD5(request.getParameter("password")));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//try to get User:
		user = userImpl.getUser(username, password);
		
		if(user != null){
			result = true;
			LOG.info("user login success");
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("password", password);
			request.setAttribute("login", username);
		}else{
			LOG.info("user login failed");
		}
		
		return result;
	}

}
